package com.leenleda.ips.activity;


import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.View;

import com.leenleda.ips.BaseActivity;
import com.leenleda.ips.R;
import com.leenleda.ips.databinding.ActivityLiveBinding;
import com.leenleda.ips.receiver.Constant;
import com.leenleda.ips.util.LogUtils;
import com.leenleda.ips.util.UShared;
import com.leenleda.ips.util.Utils;

import cn.nodemedia.NodePlayer;
import cn.nodemedia.NodePlayerDelegate;
import cn.nodemedia.NodePlayerView;


public class LiveActivity extends BaseActivity implements NodePlayerDelegate {

    @Override
    public void conTrollShow(int state, String... data) {
        switch (state){
            case Constant.RELOAD_OPEN_TIME://开机5分钟后重新加载页面
                handler.post(() -> player(1));
                break;
            case Constant.SET_MEDIA_DATA:
                LogUtils.e("SET_MEDIA_DATA", "====media=======" + data[0]);
                if (data[0].trim().equalsIgnoreCase(Constant.PUBLISH_WEB)) {
                    Utils.startActivity(this, new Intent(this, WebActivity.class));
                    finish();
                    return;
                }
                handler.post(() -> player(2));
                return;
            case Constant.LIVE_SEEK_NEXT://开机5分钟后重新加载页面
                if (binding == null || nodePlayer == null)
                    return;
                handler.post(() -> {
                    nodePlayer.seekTo(1000);
                });
                break;
        }
    }



    private ActivityLiveBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        binding = DataBindingUtil.setContentView(this, R.layout.activity_live);

        setContentView( R.layout.activity_live);
        binding = (ActivityLiveBinding) bindingView;

        binding.botL.setOnClickListener(v -> pausePlay());
        binding.botR.setOnClickListener(v -> intiPlay(playUrl));
//        intiPlay();
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.e(tag, "===player===onResume=1==" );
        showTips("");
        player(3);//"rtmp://192.168.101.138:1935/live"
    }

    private void pausePlay(){
        LogUtils.e(tag, "===player===pausePlay=1==" + nodePlayer );
        if (nodePlayer != null){
            nodePlayer.stop();
            nodePlayer.release();
            nodePlayer = null;
        }

//        onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        pausePlay();
    }



    @Override
    protected void onDestroy() {
        LogUtils.e(tag, "===player===onDestroy=1==" );
        pausePlay();
        nodePlayer = null;
        super.onDestroy();
    }

    private void showTips(String data){
        String per = Utils.getStringValue(UShared.getString(Constant.DEVICE_PERMISSION_STATE));
        if (per.isEmpty()) {
            if (data.isEmpty())
                binding.tips.setVisibility(View.GONE);
            else {
                binding.tips.setText(data);
                binding.tips.setVisibility(View.VISIBLE);
            }
        } else {
            binding.tips.setText(per);
            binding.tips.setVisibility(View.VISIBLE);
        }
    }

    private void player(int pos){
        String dataS = getData();
        String type = getType();
        LogUtils.e(tag, "===player===1===" + dataS + ",type=" + type + ",pos=" + pos);
        switch (type){
            case Constant.PUBLISH_SOURCE:
                Utils.startActivity(this, new Intent(this, ImageActivity.class));
                finish();
                return;
            case Constant.PUBLISH_WEB:
                Utils.startActivity(this, new Intent(this, WebActivity.class));
                finish();
                return;
            case Constant.PUBLISH_LIVE:
                break;
        }
        LogUtils.e(tag, "===player===1===" + dataS);//rtmp://192.168.101.138:1935/live
        if (dataS.trim().isEmpty()){
            Utils.startActivity(this, new Intent(this, WebActivity.class));
            finish();
            return;
        }
        LogUtils.e(tag, "===player===2===" + dataS);
//        try {
//            countDownTimer.cancel();
//        }catch(Exception e){
//            System.out.println("倒计时:::"+e.toString());//出现异常的处理
//        }
//        countDownTimer.start();
        intiPlay(dataS);
    }
    private String playUrl = "";

    /**
     * CountDownTimer 实现倒计时
     */
    private CountDownTimer countDownTimer = new CountDownTimer(30 * 1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            String value = String.valueOf((int) (millisUntilFinished / 1000));
            Log.e("隐藏",value);
        }

        @Override
        public void onFinish() {
        }
    };

    private NodePlayer nodePlayer;
    private void intiPlay(String dataS){
        LogUtils.e(tag, "===player===dataS=1==" + dataS + ",node=" + nodePlayer );
        playUrl = dataS;
        if (nodePlayer != null){
            nodePlayer.start();
            return;
        }
        NodePlayerView playSurface = binding.playSurface;
        //设置播放视图的渲染器模式,可以使用SurfaceView或TextureView. 默认SurfaceView
        playSurface.setRenderType(NodePlayerView.RenderType.SURFACEVIEW);
        //设置视图的内容缩放模式

        NodePlayerView.UIViewContentMode mode = null;
        mode = NodePlayerView.UIViewContentMode.ScaleToFill;//33
        playSurface.setUIViewContentMode(mode);

        nodePlayer = new NodePlayer(this,"M2FmZTEzMGUwMC00ZTRkNTMyMS1jbi5ub2RlbWVkaWEucWxpdmU=-OTv6MJuhXZKNyWWMkdKJWsVKmLHwWPcPfnRbbWGIIf+8t39TqL/mW2f5O5WdT/W8JJE7ePvkvKaS371xVckAZ/U00dSwPp8ShB8Yic2W1GhwCyq04DYETsrGnkOWrhARH7nzNhd3Eq6sVC1Fr74GCEUHbDSCZnCfhcEnzGU9InRiQJ2PImtHORahN3blAGlHb6LZmdnobw5odvKEeUhbkhxYf8S1Fv4VRnSpDCSS3LZ2U3Mp6MfGDA1ZXPadmgdwaJitIrnWA2zP/yqmlUHjMtTv8PzGcc73Tm5k5q+OMbKCJsPq8KSEpFthncvaGZJ2kS2GHx6V5TqYZglBrTx61g==");
        nodePlayer.setNodePlayerDelegate(this);
        nodePlayer.setPlayerView(playSurface);

//        String streamURL = "rtmp://192.168.101.138:1935/live/0";
//        ILog.e("FLKDSFSD", "======streamURL========" + streamURL);
        /**
         * 设置播放直播视频url
         */
        nodePlayer.setInputUrl(dataS);

        /**
         * 设置启动缓冲区时长,单位毫秒.此参数关系视频流连接成功开始获取数据后缓冲区存在多少毫秒后开始播放
         */
        nodePlayer.setBufferTime(300);

        /**
         * 设置最大缓冲区时长,单位毫秒.此参数关系视频最大缓冲时长.
         * RTMP基于TCP协议不丢包,网络抖动且缓冲区播完,之后仍然会接受到抖动期的过期数据包.
         * 设置改参数,sdk内部会自动清理超出部分的数据包以保证不会存在累计延迟,始终与直播时间线保持最大maxBufferTime的延迟
         */
        nodePlayer.setMaxBufferTime(1000);


        /**
         *
         开启硬件解码,支持4.3以上系统,初始化失败自动切为软件解码,默认开启.
         */
        nodePlayer.setHWEnable(true);

        /**
         * 设置连接超时时长,单位毫秒.默认为0 一直等待.
         * 连接部分RTMP服务器,握手并连接成功后,当播放一个不存在的流地址时,会一直等待下去.
         * 如需超时,设置该值.超时后返回1006状态码.
         */
        // np.setConnectWaitTimeout(10*1000);

        /**
         * @brief rtmpdump 风格的connect参数
         * Append arbitrary AMF data to the Connect message. The type must be B for Boolean, N for number, S for string, O for object, or Z for null.
         * For Booleans the data must be either 0 or 1 for FALSE or TRUE, respectively. Likewise for Objects the data must be 0 or 1 to end or begin an object, respectively.
         * Data items in subobjects may be named, by prefixing the type with 'N' and specifying the name before the value, e.g. NB:myFlag:1.
         * This option may be used multiple times to construct arbitrary AMF sequences. E.g.
         */
        // np.setConnArgs("S:info O:1 NS:uid:10012 NB:vip:1 NN:num:209.12 O:0");

        /**
         * 设置RTSP使用TCP传输模式
         * 支持的模式有:
         * NodePlayer.RTSP_TRANSPORT_UDP
         * NodePlayer.RTSP_TRANSPORT_TCP
         * NodePlayer.RTSP_TRANSPORT_UDP_MULTICAST
         * NodePlayer.RTSP_TRANSPORT_HTTP
         */
        nodePlayer.setRtspTransport("udp");

        /**
         * 设置视频解密秘钥，16字节，空字符串则不进行解密
         */
        nodePlayer.setCryptoKey("");

        /**
         * 在本地开起一个RTMP服务,并进行监听播放,局域网内其他手机或串流器能推流到手机上直接进行播放,无需中心服务器支持
         * 播放的ip可以是本机IP,也可以是0.0.0.0,但不能用127.0.0.1
         * app/stream 可加可不加,只要双方匹配就行
         */
        // np.setLocalRTMP(true);
        nodePlayer.start();
        new Handler().postDelayed(() -> {
            scrollCheck();
        }, 1000);
    }

    private boolean isStarting;
    @Override
    public void onEventCallback(NodePlayer player, int event, String msg) {
        LogUtils.e(tag, "====onEventCallback===" + event + ",msg=" + msg);
        switch (event){
            case 1000: // 正在连接视频
                break;
            case 1001: // 视频连接成功
                isStarting = true;
                break;
            case 1002: // 视频连接失败 流地址不存在，或者本地网络无法和服务端通信，回调这里。5秒后重连， 可停止
                break;
            case 1003:// 视频开始重连,自动重连总开关
                break;
            case 1004:// 视频播放结束
                isStarting = false;
                break;
            case 1005:// 网络异常,播放中断,播放中途网络异常，回调这里。1秒后重连，如不需要，可停止
                break;
        }
    }

}
